<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NBA Predictions Chatbot</title>
    <style>
        /* Core styles */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f0f0;
        }

        .chat-container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .chat-header {
            background-color: #1d428a;
            color: white;
            padding: 20px;
            text-align: center;
        }

        .chat-messages {
            padding: 20px;
            height: 500px;
            overflow-y: auto;
        }

        /* Message styles */
        .message {
            margin-bottom: 12px;
            padding: 8px 12px;
            border-radius: 12px;
            max-width: 90%;
        }

        .user-message {
            background-color: #007AFF;
            color: white;
            margin-left: auto;
        }

        .bot-message {
            background-color: #E9ECEF;
            color: black;
        }

        /* Prediction card styles */
        .prediction-card {
            background-color: #f8f9fa;
            border-left: 4px solid #1d428a;
            padding: 8px;
            margin: 8px 0;
            border-radius: 6px;
        }

        .matchup {
            font-weight: bold;
            color: #1d428a;
        }

        .prediction-details {
            display: flex;
            flex-direction: column;
            gap: 3px;
        }

        .betting-lines {
            margin-top: 4px;
        }

        /* Betting lines pills */
        .spread-pill, .over-under-pill {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            margin: 2px 4px;
            background-color: #e9ecef;
        }

        .spread-pill {
            color: #198754;
            border: 1px solid #198754;
        }

        .over-under-pill {
            color: #dc3545;
            border: 1px solid #dc3545;
        }

        /* Input container */
        .input-container {
            padding: 20px;
            border-top: 1px solid #ddd;
            display: flex;
            gap: 10px;
        }

        input[type="text"] {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }

        button {
            padding: 10px 20px;
            background-color: #1d428a;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        /* Loading indicator */
        .loader {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-radius: 50%;
            border-top: 3px solid #1d428a;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .typing-indicator {
            background-color: #E9ECEF;
            padding: 8px 12px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            margin-bottom: 12px;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <h1>🏀 NBA Predictions Bot</h1>
        </div>
        <div class="chat-messages" id="chat-messages">
            <div class="message bot-message">
                <div class="welcome-header">
                    <img src="https://cdn.nba.com/logos/nba/nba-logoman-75-word_white.svg" alt="NBA Logo" class="nba-logo">
                    <h2>Welcome to NBA Predictions!</h2>
                </div>
                <p class="intro-text">Hi! I'm your NBA predictions assistant. Ask me about any NBA games and I'll help you with predictions!</p>
                
                <div class="examples-container">
                    <p class="examples-header">Here are some examples of what you can ask:</p>
                    <ul class="examples-list">
                        <li><span class="example-bullet">🏀</span> "What are the predictions for today's NBA games?"</li>
                        <li><span class="example-bullet">🏀</span> "What are the predictions for tomorrow's games?"</li>
                        <li><span class="example-bullet">🏀</span> "What are the predictions for the Celtics game today?"</li>
                        <li><span class="example-bullet">🏀</span> "What are the predictions for the NBA games on Jan 27?"</li>
                    </ul>
                </div>
                <style>
                    .welcome-header {
                        display: flex;
                        align-items: center;
                        margin-bottom: 15px;
                        background: linear-gradient(135deg, #1d428a 0%, #c9082a 100%);
                        padding: 15px;
                        border-radius: 10px;
                        color: white;
                    }
                    .nba-logo {
                        height: 40px;
                        margin-right: 15px;
                    }
                    .welcome-header h2 {
                        margin: 0;
                        font-size: 1.5em;
                    }
                    .intro-text {
                        font-size: 1.1em;
                        margin: 15px 0;
                        color: #333;
                        line-height: 1.4;
                    }
                    .examples-container {
                        background-color: #f8f9fa;
                        padding: 15px;
                        border-radius: 10px;
                        border-left: 4px solid #1d428a;
                    }
                    .examples-header {
                        font-weight: bold;
                        color: #1d428a;
                        margin-bottom: 10px;
                    }
                    .examples-list {
                        list-style: none;
                        padding: 0;
                        margin: 0;
                    }
                    .examples-list li {
                        margin: 8px 0;
                        padding-left: 25px;
                        position: relative;
                    }
                    .example-bullet {
                        position: absolute;
                        left: 0;
                        color: #c9082a;
                    }
                </style>
            </div>
        </div>
        <div class="input-container">
            <input type="text" id="user-input" placeholder="Type your message here..." onkeypress="handleKeyPress(event)">
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>

    <script>
        const API_URL = window.location.origin + '/api/nba_agent';
        const API_TOKEN = 'test123'; 
        const messagesContainer = document.getElementById('chat-messages');
        const userInput = document.getElementById('user-input');

        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        function formatPrediction(content) {
            if (content.includes("🏀")) {
                const predictions = content.split("🏀")
                    .filter(p => p.trim())
                    .filter(p => p.includes("Winner:"));
                
                let allPredictions = '';
                
                predictions.forEach(predictionPart => {
                    const matchupPattern = /(.*?) \(Away\) @ (.*?) \(Home\)/;
                    const matchupMatch = predictionPart.match(matchupPattern);
                    const matchup = matchupMatch ? `🏀 ${matchupMatch[0]}` : '';

                    if (matchup && predictionPart.includes("Winner:")) {
                        const bettingLinesSection = predictionPart.split("Betting Lines:")[1] || '';
                        const lines = bettingLinesSection.trim().split('\n');
                        
                        let spread = '';
                        let overUnder = '';
                        
                        if (lines.length >= 2) {
                            spread = lines[0].trim();
                            overUnder = lines[1].trim();
                        }

                        allPredictions += `
                            <div class="prediction-card">
                                <div class="matchup">${matchup}</div>
                                <div class="prediction-details">
                                    <div class="winner"><strong>Winner:</strong> ${predictionPart.match(/Winner: (.*?)(?:\n|$)/)?.[1] || ''}</div>
                                    <div class="analysis"><strong>Analysis:</strong> ${predictionPart.match(/Analysis: (.*?)(?:\n|$)/)?.[1] || ''}</div>
                                    <div class="confidence"><strong>Confidence:</strong> ${predictionPart.match(/Confidence: (.*?)(?:\n|$)/)?.[1] || ''}</div>
                                    ${bettingLinesSection ? `
                                        <div class="betting-lines">
                                            <div class="betting-header">Betting Lines:</div>
                                            ${spread ? `<div class="spread-pill">${spread}</div>` : ''}
                                            ${overUnder ? `<div class="over-under-pill">${overUnder}</div>` : ''}
                                        </div>
                                    ` : ''}
                                </div>
                            </div>
                        `;
                    }
                });

                return allPredictions || `<div class="regular-message">${content}</div>`;
            }
            return `<div class="regular-message">${content}</div>`;
        }

        function addMessage(content, isUser) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;
            messageDiv.innerHTML = isUser ? content : formatPrediction(content);
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        function showLoadingIndicator() {
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'typing-indicator';
            loadingDiv.id = 'loading-indicator';
            loadingDiv.innerHTML = `
                <div class="loader"></div>
                <span>Getting prediction...</span>
            `;
            messagesContainer.appendChild(loadingDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        function removeLoadingIndicator() {
            const loadingDiv = document.getElementById('loading-indicator');
            if (loadingDiv) {
                loadingDiv.remove();
            }
        }

        async function sendMessage() {
            const userInput = document.getElementById('user-input').value;
            if (!userInput.trim()) return;

            addMessage(userInput, true);
            userInput.value = '';
            showLoadingIndicator();

            try {
                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${API_TOKEN}`  // Make sure this matches exactly
                    },
                    body: JSON.stringify({
                        query: userInput,
                        user_id: 'test-user',
                        request_id: Date.now().toString(),
                        session_id: 'test-session'
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(`HTTP error! status: ${response.status}, message: ${errorData.detail || 'Unknown error'}`);
                }

                const data = await response.json();
                console.log('Backend Response:', data);

                await new Promise(resolve => setTimeout(resolve, 1000));

                const supabaseResponse = await fetch('https://hoggvadeoyewxentvxxe.supabase.co/rest/v1/messages?select=*&order=created_at.desc&limit=1', {
                    headers: {
                        'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImhvZ2d2YWRlb3lld3hlbnR2eHhlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Mzc3NjI2MzgsImV4cCI6MjA1MzMzODYzOH0.EHwCD4vtKlrytanLEfyUnJZOvvXCyj3RAsNRsS-BzMg',
                        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImhvZ2d2YWRlb3lld3hlbnR2eHhlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Mzc3NjI2MzgsImV4cCI6MjA1MzMzODYzOH0.EHwCD4vtKlrytanLEfyUnJZOvvXCyj3RAsNRsS-BzMg'
                    }
                });

                const messages = await supabaseResponse.json();
                console.log('Supabase Messages:', messages);

                removeLoadingIndicator();

                if (messages && messages.length > 0 && messages[0].message) {
                    const aiMessage = messages[0].message.content;
                    addMessage(aiMessage, false);
                } else {
                    addMessage("I'm sorry, I couldn't process your request at this time.", false);
                }

            } catch (error) {
                console.error('Error:', error);
                removeLoadingIndicator();
                addMessage('Sorry, I encountered an error processing your request.', false);
            }
        }
    </script>
</body>
</html>